package mya.mes.mdc.model.tag.values;


import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

public class ViewTagValues {

    public final HashMap<String, ViewTagValue> map = new HashMap<>();


    public final String dateSeq;

    public final String date;

    public final String time;


    /**
     * 接收到的MQTT消息的存储到mongodb的_id
     */
    public final Long mqttSavedId;
    /**
     * 接收到的MQTT消息的存储到mongodb的CollectionName
     */
    public final String mqttSavedColl;

    public MdcTagValues mdcTagValues;


    public ViewTagValues(MdcTagValues mdcTagValues, String mqttSavedColl, Long mqttSavedId) {
        this.mqttSavedColl = mqttSavedColl;
        this.mqttSavedId = mqttSavedId;
        this.mdcTagValues = mdcTagValues;

        Instant instant = Instant.ofEpochMilli(mqttSavedId);
        LocalDateTime today = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();

        dateSeq = today.format(DateTimeFormatter.BASIC_ISO_DATE);
        date = today.format(DateTimeFormatter.ISO_LOCAL_DATE);
        String timeTmp = today.format(DateTimeFormatter.ISO_TIME);
        if (timeTmp.length() > "HH:mm:ss".length()) {
            timeTmp = timeTmp.substring(0, "HH:mm:ss".length());
        }
        time = timeTmp;
        convert();
    }


    private synchronized void convert() {
        if (mdcTagValues.valueList == null) {
            return;
        }
        mdcTagValues.valueList.forEach(mdcTagValue -> {
            String key = mdcTagValue.mdcTag.buildKey();
            ViewTagValue value = map.get(key);
            if (value == null) {
                value = new ViewTagValue();
                value.viewTag = mdcTagValue.mdcTag.viewTag;
                //注意：对应于System 报警等，没有对应的ViewTag
                if (value.viewTag == null) {
                    value.viewTagName = mdcTagValue.mdcTag.buildKey();
                } else {
                    value.viewTagName = value.viewTag.tagName;
                }
                map.put(key, value);
            }
            value.add(mdcTagValue);
        });
    }


    public boolean hasAlarm() {
        for (ViewTagValue value : map.values()) {
            if (value.hasAlarm()) {
                return true;
            }
        }
        return false;
    }

    public boolean hasStartAlarm() {
        for (ViewTagValue value : map.values()) {
            if (value.hasStartAlarm()) {
                return true;
            }
        }
        return false;
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }
}
